package net.xxcl.kygl.controller;

import net.xxcl.kygl.pojo.Money;
import net.xxcl.kygl.pojo.Project;
import net.xxcl.kygl.service.MoneyService;
import net.xxcl.kygl.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * User: 夏汛
 * Date: 12-11-4
 * Time: 下午10:32
 */
@Controller
@RequestMapping("/money")
public class MoneyController {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private MoneyService moneyService;

    /**
     * 经费开支
     * @param money
     * @return
     */
    @RequestMapping(value = "/reduce",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> reduce(@ModelAttribute("money") Money money){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Project project = projectService.selectByPrimaryKey(money.getProjectid());
        double left = 0;
        if(project.getMoney()!=null){
            left += project.getMoney();
        }
        if(project.getShoolmoney()!=null){
            left += project.getShoolmoney();
        }
        double remain = 0;
        if(project.getRemain()!=null){
            remain += project.getRemain();
        }
        if((left-remain)<money.getMoney()){
            responseMap.put("info", "剩余金额不足");
        } else {
            project.setRemain(remain+money.getMoney());
            moneyService.reduce(money,project);
            responseMap.put("info", "提交成功");
        }
        responseMap.put("success", true);
        return responseMap;
    }

    /**
     * 设置课题经费和配套经费
     * @param projectid
     * @param money
     * @param schoolmoney
     * @return
     */
    @RequestMapping(value = "/addMoneyAndSchoolMoney",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> addMoneyAndSchoolMoney(
                            @RequestParam(value = "projectid") Integer projectid,
                            @RequestParam(value = "money",required = false) Double money,
                            @RequestParam(value = "schoolmoney",required = false) Double schoolmoney){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Project project = new Project();
        project.setId(projectid);
        if(money!=null){
            project.setMoney(money);
            projectService.updateByPrimaryKeySelective(project);
            responseMap.put("info", "提交成功");
        } else if (schoolmoney!=null){
            project.setShoolmoney(schoolmoney);
            projectService.updateByPrimaryKeySelective(project);
            responseMap.put("info", "提交成功");
        } else {
            responseMap.put("info", "没有设置金额");
        }
        responseMap.put("success", true);
        return responseMap;
    }
}
